package com.furnitur.core.service.impl;

import com.furnitur.core.service.FileService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.public-url}")
    private String publicUrl;

    @Override
    public String uploadImage(MultipartFile file) throws Exception {
        try {
            // 生成文件名
            String fileName = generateFileName(file.getOriginalFilename());
            
            // 检查bucket是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // 创建bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                
                // 设置bucket策略为公共读
                String policy = String.format(
                    "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::%s/*\"]}]}",
                    bucketName
                );
                minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                        .bucket(bucketName)
                        .config(policy)
                        .build()
                );
            }

            log.info("开始上传文件到MinIO: {}", fileName);
            
            // 上传文件
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            
            String fileUrl = String.format("%s/%s/%s", publicUrl, bucketName, fileName);
            log.info("文件上传成功，URL: {}", fileUrl);
            
            // 返回文件访问路径
            return fileUrl;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }
    
    private String generateFileName(String originalFilename) {
        if (originalFilename == null) {
            throw new RuntimeException("文件名不能为空");
        }
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return "avatars/" + UUID.randomUUID().toString().replaceAll("-", "") + extension;
    }
}